import React from "react";
import { LeftOutline } from "antd-mobile-icons"; // icon
import { isLogin } from "@u/index";
import { Form, Input, Button, Toast, NavBar } from "antd-mobile"; //组件
import { useNavigate, useDispatch } from "umi"; // 路由
import { getLoginApi } from "@/api";

export default function index() {
  /* 仓库 */
  const dispatch = useDispatch();
  /* 路由 */
  const navigate = useNavigate();

  /* 表单提交 触发 callBack */
  const onFinish = async (values: any) => {
    const res = await getLoginApi(values);
    if (res.data.code == "200") {
      Toast.show({
        content: "登录成功！",
        afterClose: () => {
          localStorage.setItem("token", res.data.data.token);
          localStorage.setItem("userId", res.data.data.user.id);
          dispatch({
            // token 存储到仓库中
            type: "user/setToken",
            token: res.data.data.token,
          });
          navigate("/home");
        },
      });
    } else {
      Toast.show({
        content: res.data.msg,
      });
    }
  };
  // 返回首页
  const back = () => navigate("/home");
  return (
    <div className="fromLogin">
      <NavBar onBack={back}>登录页</NavBar>
      <Form layout="horizontal" onFinish={onFinish}>
        <Form.Item
          name="name"
          label="账号"
          rules={[{ required: true, message: "账号不能为空" }]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input placeholder="请输入密码" />
        </Form.Item>
        <Form.Item className="button">
          <Button style={{ width: "100PX" }} type="submit" color="danger">
            登录
          </Button>
          <Button
            style={{ width: "100PX" }}
            color="primary"
            onClick={() => navigate("/register")}
          >
            注册
          </Button>
          <Button
            style={{ width: "100PX" }}
            color="warning"
            onClick={() => navigate("/findPassword")}
          >
            找回密码
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
